import { RequestConfig } from '@umijs/max';
import axios from 'axios';

export const layout = {
    title: '图书管理系统',
    locale: false,
    siderWidth: 208,
    pwa: false,
    navTheme: 'light',
    primaryColor: '#1890ff',
    layout: 'mix',
    contentWidth: 'Fluid',
    fixedHeader: false,
    splitMenus: false,
    theme: {
      token: {
        colorPrimary: '#1890ff',
        borderRadius: 6,
      },
    },
  };

// 全局请求配置
export const request: RequestConfig = {
  timeout: 10000,
  // 请求前的拦截
  requestInterceptors: [
    (url: string, config: RequestConfig) => {
      // 从localStorage获取token
      let result = { url, options: { ...config } };

      // 确保API请求有正确的前缀
      if (!url.startsWith('/api/') && !url.startsWith('http')) {
        url = '/api' + (url.startsWith('/') ? url : '/' + url);
      }

      if (!url.includes('/login') && !url.includes('/api/auth/login/')) {
        const token = localStorage.getItem('token');
        if (!token) {
          // token 异常
          result.options.cancelToken = axios.CancelToken.source().token;
        } else {
          // 正常请求
          result.options.headers = { 
            ...result.options.headers,
            Authorization: `Bearer ${token}` 
          };
        }
      }

      return { url, options: result.options };
    },
  ],
  // 响应后的拦截
  responseInterceptors: [
    (response:any) => {
      // 处理响应数据
      if (response.status >= 200 && response.status < 300) {
        return response; // 直接返回数据
      } else {
        throw new Error()
      }
    },
  ],
  // 错误处理
  errorConfig: {
    errorHandler: (resData) => {
      return {
        success: false,
        errorMessage: resData.message || '请求失败',
        errorCode: 500,
      };
    },
  },
};

// 全局初始化数据
export async function getInitialState() {
  const token = localStorage.getItem('token');
  const userInfo= localStorage.getItem('user');
  
  return {token,userInfo}
  };

